<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { ref, nextTick, watch, onUnmounted } from "vue";
import { Api } from "@/apis"
import { ArticleDetailDataType, CommentDetailType, ArticleStoreType } from "@/typing";
import { titleTypes } from "@/datas/index";
import { homeStoriesStore, audioStoriesStore } from "../../store";
import { storeToRefs } from "pinia";
import { booksImageArr } from "@/utils/imgSrcArr";
import ArticleIcon from "@/components/icon/ArticleIcon.vue";

const audioStore = audioStoriesStore();
const { updateIsPlayOrPauseStore, updateIsAudioSrcStore, updateShowDiscStore } = audioStore

const store = homeStoriesStore();
const { articleId, category } = storeToRefs(store)
const { updateComment } = store

const router = useRouter()
const durationStr = ref<string>('');
const duration = ref<number>(0);
const list = ref<ArticleDetailDataType>();
const comment = ref<CommentDetailType>();
const isLoading = ref<boolean>(true);
let listObj = ref<ArticleStoreType>();

let discTimer = 0;
let discImageIndex = ref<number>(0);

function goBackFunc() {
    router.go(-1);
}

watch(() => articleId.value, (newValue) => {
    isLoading.value = true;
    render(newValue, category.value);

    setTimeout(() => {
        isLoading.value = false;
    }, 1500);
})

setTimeout(() => {
    isLoading.value = false;
}, 1500);

render(articleId.value, category.value);

if (isLoading.value) {
    discTimer = setInterval(() => {
        discImageIndex.value = (discImageIndex.value + 1) % booksImageArr.length;
    }, 80);
}
else {
    if (discTimer) {
        // 清除副作用计时器
        clearInterval(discTimer);
    }
}

// 重新渲染列表
async function render(id: string, category: string) {
    const data = await Api.getArticleDetail(id, category);

    if (data) {
        list.value = data.data.data;
        console.log(list.value);

        listObj.value = {
            category,
            id: list.value.id,
            title: list.value.title,
            subTitle: list.value.author_list[0].user_name
        }
        let commentData = await Api.getArticleRatings(id, category);
        comment.value = commentData?.data.data;

        updateComment(comment.value?.count || 0, comment.value?.data || []);
        await nextTick()
    }
}

// 设置日期格式
function getAudioDuration(e: any) {
    duration.value = e.target.duration;
    const m = Math.floor(duration.value / 60);
    const s = Math.floor(duration.value % 60);

    let minus = m >= 10 ? m + '' : "0" + m;
    let second = s >= 10 ? s + '' : "0" + s;

    durationStr.value = minus + ":" + second;
}

// 开启全局音频
function playAudio(src: string, title: string, anchor: string) {
    updateIsPlayOrPauseStore(true);
    updateIsAudioSrcStore(src, title, anchor);
    updateShowDiscStore(true);
}

// 组件将要销毁之前清空计时器
onUnmounted(() => {
    if (discTimer) {
        // 清除副作用计时器
        clearInterval(discTimer);
    }
})

</script>

<template>
    <div>
        <div class="p-5 flex items-center ">
            <img class="w-6 h-10" src="@/assets/card/h5_qr_back.png" alt="back" @click="goBackFunc">
            <div class="text-center text-2xl w-11/12 ">{{ titleTypes[category] }}</div>
            <ArticleIcon v-if="(listObj !== undefined)" :obj="listObj" />
        </div>

        <div v-show="isLoading">
            <div class=" disc-icon h-32 w-36 absolute top-64 left-64"
                :style="{ backgroundImage: `url(${booksImageArr[discImageIndex]})` }">
            </div>
        </div>

        <div v-show="!isLoading">
            <div class="text-3xl font-bold my-10 ml-5 ">{{ list?.title }}</div>
            <div class="ml-5 pb-10 ">文 / {{ list?.author_list[0].user_name }}</div>

            <div v-if="list?.audio && category !== '8'"
                @click="playAudio(list?.audio || '', list?.title || '', list?.anchor || '')"
                class="flex justify-between border border-black w-11/12  ml-6 px-8 py-4 rounded-xl">

                <div>有声阅读 | {{ list?.anchor }} </div>
                <div>{{ durationStr }}</div>
                <audio v-if="list?.audio" :src="list?.audio" @canplay="getAudioDuration"></audio>
            </div>

            <div v-html="list?.json_content.content" class="mt-12 content-html "> </div>
        </div>
    </div>
</template>